Implementing Authentication and Authorization in Spring Boot
Course: Advanced Java Training
Topic: Implementing Authentication and Authorization
Course Link: Advanced Java Training at JustAcademy
Demo Registration: Register for a Course Demo
Website: Visit JustAcademy
1. Introduction to Authentication and Authorization
Authentication and authorization are two essential security mechanisms used to protect web applications, REST APIs, and enterprise systems. They help ensure that users are correctly identified and can access only the resources and operations permitted to them.
Spring Boot applications commonly use Spring Security to implement these mechanisms. Spring Security provides configurable filters, authentication providers, password encoding, session management, and access-control rules.
For example, in an employee management system, an employee may be allowed to view their own profile, while an administrator may be permitted to create employees, update records, and manage user accounts.
Learning Objectives
- Understand the difference between authentication and authorization.
- Learn the architecture and working of Spring Security.
- Configure application security using
SecurityFilterChain.
- Implement username-and-password authentication.
- Configure secure password storage using
PasswordEncoder.
- Apply role-based and authority-based access control.
- Secure REST endpoints and service methods.
- Understand sessions, bearer tokens, JWT validation, and CSRF protection.
- Test authentication and authorization using Spring Security testing tools.
2. What Is Authentication?
Authentication is the process of verifying the identity of a user, application, or system. It checks whether the supplied credentials or identity evidence are valid.
Common authentication methods include:
- Username and password: The user submits a username and password.
- Session-based authentication: The server maintains authenticated session state after login.
- HTTP Basic authentication: Credentials are sent in an HTTP Authorization header. HTTPS is essential because Basic authentication does not encrypt the credentials itself.
- Token-based authentication: The client sends an access token with requests to protected resources.
- Multi-factor authentication: The user verifies identity using two or more authentication factors.
- OpenID Connect: An identity layer commonly used to authenticate users through an identity provider.
Example
A user submits a username and password to a login endpoint. The application loads the relevant user record and verifies the submitted password against its stored password hash. If the credentials are valid, the configured authentication mechanism establishes an authenticated identity.
Important: Passwords must never be stored in plain text or written to application logs.
3. What Is Authorization?
Authorization determines what an authenticated user is allowed to access or perform. It evaluates the user's roles, authorities, permissions, or other access policies.
For example:
- A public visitor can view public information.
- An authenticated user can view permitted account information.
- A manager can access authorized team reports.
- An administrator can manage application users.
Authentication vs. Authorization
| Feature |
Authentication |
Authorization |
| Purpose |
Verifies identity. |
Determines access permissions. |
| Main question |
Who are you? |
What are you allowed to do? |
| Example |
Verifying a submitted password. |
Checking whether a user has the ADMIN role. |
| Typical failure |
Invalid or missing credentials. |
The user lacks the required permission. |
| Spring Security concepts |
Authentication providers, AuthenticationManager, UserDetailsService. |
Request matchers, GrantedAuthority, AuthorizationManager, method security. |
4. Introduction to Spring Security
Spring Security is a framework that provides authentication, authorization, and protection against common security threats in Spring applications. In servlet-based applications, it uses a chain of filters to process incoming HTTP requests.
Security processing generally includes loading the security context, applying relevant security protections, authenticating requests when necessary, and evaluating authorization rules. The exact filters depend on the configured authentication mechanisms and application requirements.
Important Spring Security Components
| Component |
Purpose |
SecurityFilterChain |
Defines the filters and security rules applied to matching HTTP requests. |
Authentication |
Represents an authentication request or an authenticated principal with granted authorities. |
AuthenticationManager |
Coordinates authentication using configured providers. |
AuthenticationProvider |
Performs a specific type of authentication. |
UserDetailsService |
Loads user information for username-based authentication. |
UserDetails |
Represents user information, encoded password data, account status, and authorities. |
PasswordEncoder |
Encodes passwords for storage and verifies submitted passwords. |
SecurityContextHolder |
Provides access to the current security context. |
GrantedAuthority |
Represents a role or permission granted to a user. |
AuthorizationManager |
Evaluates access-control decisions for protected requests or methods. |
5. Adding Spring Security Dependencies
In a Maven-based Spring Boot project, add the Spring Security starter. Spring Boot manages compatible dependency versions through its dependency management configuration.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
For REST endpoints, include Spring Web:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
If user records are stored in a relational database, the project may also require Spring Data JPA, a database driver, and an appropriate persistence configuration.
6. Configuring Security Using SecurityFilterChain
Modern Spring Security applications commonly define HTTP access rules through a SecurityFilterChain bean. This allows developers to specify which routes are public, which require authentication, and which require particular roles.
Example Configuration
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(
HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/public/**").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.httpBasic(Customizer.withDefaults());
return http.build();
}
}
Explanation
@Configuration declares a Spring configuration class.
@Bean registers the security filter chain.
permitAll() allows matching requests without authentication.
hasRole("ADMIN") requires the ADMIN role.
authenticated() requires an authenticated user.
httpBasic() enables HTTP Basic authentication.
This example uses HTTP Basic for simplicity. In a production environment, protect it with HTTPS and choose the authentication mechanism appropriate to the client. Browser applications may use form login, while APIs may use a properly configured OAuth 2.0 resource server.
7. Creating Users for Authentication
Spring Security supports several ways to load user information, including in-memory users, database-backed users, LDAP, and custom authentication providers.
In-Memory Authentication
In-memory authentication is useful for learning, demonstrations, and automated tests. It is generally unsuitable as the primary user-management mechanism for a production application.
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Configuration
public class UserConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories
.createDelegatingPasswordEncoder();
}
@Bean
public UserDetailsService userDetailsService(
PasswordEncoder passwordEncoder) {
UserDetails user = User.withUsername("employee")
.password(passwordEncoder.encode("ExampleUserPassword!"))
.roles("USER")
.build();
UserDetails admin = User.withUsername("administrator")
.password(passwordEncoder.encode("ExampleAdminPassword!"))
.roles("ADMIN")
.build();
return new InMemoryUserDetailsManager(user, admin);
}
}
The example creates a USER and an ADMIN account. These are demonstration credentials only. Do not use hardcoded passwords in production; configure accounts through a secure user-management process and store credentials in a protected user store.
8. Understanding PasswordEncoder
A PasswordEncoder applies a one-way password-hashing algorithm to a password before it is stored. During login, Spring Security verifies the submitted password against the stored encoded value.
Common Password-Hashing Options
- BCrypt: An adaptive password-hashing algorithm commonly used for application passwords.
- Argon2: A memory-hard password-hashing algorithm.
- PBKDF2: A password-based key derivation function.
- DelegatingPasswordEncoder: Supports encoding identifiers and delegates to configured encoders, which can help with migration between password-hashing formats.
Encoding and Verifying a Password
String rawPassword = "ExamplePassword!";
String encodedPassword =
passwordEncoder.encode(rawPassword);
boolean passwordMatches = passwordEncoder.matches(
rawPassword, encodedPassword);
The encoded value is stored in the user database. The application uses matches() to verify a submitted password against that stored value.
Best practice: Never store plain-text passwords or use a fast general-purpose hash such as plain SHA-256 as the sole password-storage mechanism. Use a suitable adaptive password-hashing implementation and follow its configuration guidance.
9. Understanding the Authentication Flow
A typical username-and-password authentication process follows these steps:
- The user submits credentials through a login form or authentication request.
- The request passes through the configured Spring Security filters.
- The relevant authentication filter creates an authentication request.
- The
AuthenticationManager delegates the request to a suitable provider.
- The provider loads the user's information from the configured user store.
- The submitted password is verified against the stored encoded password.
- If verification succeeds, Spring Security establishes an authenticated security context according to the configured mechanism.
- The authorization rules determine whether the authenticated user can access the requested resource.
If authentication fails, access is not granted. The resulting response depends on the configured authentication entry point and whether the application uses a browser-oriented login flow or an API-oriented flow.
10. Implementing Role-Based Authorization
Role-based access control (RBAC) assigns roles to users and uses those roles to determine which application features they can access.
| Role |
Example Permissions |
Example Endpoint |
| USER |
View permitted account and profile information. |
/user/profile |
| MANAGER |
View authorized team reports. |
/manager/reports |
| ADMIN |
Manage application users and administrative settings. |
/admin/users |
Defining Role-Based Rules
http.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/public/**").permitAll()
.requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.requestMatchers("/manager/**").hasAnyRole("MANAGER", "ADMIN")
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
);
By convention, hasRole("ADMIN") checks for the authority ROLE_ADMIN. Spring Security adds the standard role prefix for this expression. If an application uses exact permission names, hasAuthority("REPORT_READ") can check the specified authority directly.
Define access rules carefully and verify that sensitive routes are not accidentally made public by broader matchers.
11. Role-Based Access vs. Authority-Based Access
| Feature |
Role-Based Access |
Authority-Based Access |
| Meaning |
Uses a role representing a group of permissions. |
Uses a specific granted permission or authority. |
| Example |
ROLE_ADMIN |
REPORT_READ |
| Expression |
hasRole("ADMIN") |
hasAuthority("REPORT_READ") |
| Typical use |
Broad access categories. |
Fine-grained access control. |
For example, an ADMIN role may include several authorities such as USER_CREATE, USER_UPDATE, and REPORT_READ. The application determines how roles and authorities are associated with users.
12. Implementing Method-Level Security
Request-level authorization protects HTTP routes. Method-level security protects selected service methods and supports more fine-grained checks involving method arguments, return values, and the authenticated identity.
Enable Method Security
package com.example.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
@Configuration
@EnableMethodSecurity
public class MethodSecurityConfig {
}
Adding the Spring Security starter does not enable method-level authorization automatically; configure it explicitly when required.
Protect Service Methods
package com.example.demo.service;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Service;
@Service
public class AdminService {
@PreAuthorize("hasRole('ADMIN')")
public String performAdministrativeTask() {
return "Administrative task completed";
}
@PreAuthorize("hasAuthority('REPORT_READ')")
public String viewRestrictedReport() {
return "Restricted report data";
}
}
@PreAuthorize checks the authorization expression before the method executes. Method security is commonly implemented through Spring AOP proxies, so self-invocation within the same object may bypass proxy-based security interception. Test service boundaries carefully.
13. Creating Protected REST Endpoints
A REST controller defines endpoints that can be protected by the rules configured in Spring Security.
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class SecureController {
@GetMapping("/public")
public String publicEndpoint() {
return "This endpoint is available publicly.";
}
@GetMapping("/profile")
public String profileEndpoint() {
return "This endpoint requires authentication.";
}
@GetMapping("/admin")
public String adminEndpoint() {
return "This endpoint requires administrator access.";
}
}
When the controller is combined with suitable security matchers, the public endpoint can be accessed without authentication, the profile endpoint requires authentication, and the administrator endpoint requires the ADMIN role.
For production APIs, return structured response objects and avoid exposing confidential information unless the current user is authorized to receive it.
14. Handling Unauthorized and Forbidden Requests
HTTP status codes help clients understand security failures.
| Status |
Meaning |
Typical Situation |
| 401 Unauthorized |
Authentication is required or valid authentication has not been established. |
A protected API request contains no acceptable credentials. |
| 403 Forbidden |
The request is not permitted. |
An authenticated user lacks the required role or permission. |
The exact response depends on the configured authentication mechanism. A browser login flow may redirect the user to a login page instead of returning a JSON response.
Example Access-Denied Handler
http.exceptionHandling(exception -> exception
.accessDeniedHandler((request, response, accessDeniedException) -> {
response.setStatus(403);
response.setContentType("application/json");
response.getWriter().write(
"{\"error\":\"Access denied\",\"status\":403}");
})
);
This handler customizes the response for access-denied exceptions. A complete application should use a consistent API error format and avoid returning internal exception details to clients.
15. Session-Based Authentication
Session-based authentication is common in traditional web applications. After a successful login, the server maintains authenticated session state and the browser sends a session cookie with subsequent requests.
Typical Session Flow
- The user submits login credentials.
- The application validates the credentials.
- The server establishes an authenticated session.
- The browser sends the session cookie on later requests.
- Spring Security uses the session's security context to identify the user.
- The session expires or is invalidated when the applicable policy requires it.
Session Security Best Practices
- Use HTTPS across the application.
- Set appropriate cookie attributes such as
Secure, HttpOnly, and SameSite.
- Configure session expiration and session-fixation protection.
- Invalidate the session during logout when using session-based authentication.
- Keep CSRF protection enabled where browser-managed credentials make it necessary.
Spring Security enables CSRF protection by default in common servlet configurations. Do not disable it simply because an application exposes REST endpoints. Assess the actual authentication mechanism and whether browsers automatically send credentials with requests.
16. Token-Based Authentication and JWT
Token-based authentication is frequently used in REST APIs and distributed applications. After a user or client is authenticated, an identity system may issue an access token for requests to protected resources.
JSON Web Token (JWT) is one format used for representing claims. A JWT may be signed, and a resource server must validate it before trusting its contents.
Example Bearer Token Request
GET /api/profile
Authorization: Bearer <access-token>
JWT Validation Requirements
- Validate the token signature using a trusted key.
- Validate the expected issuer.
- Validate the intended audience when applicable.
- Check token expiration and relevant time-based claims.
- Accept only the intended cryptographic algorithms and reject unexpected ones.
- Protect tokens in transit with HTTPS.
- Avoid placing access tokens in URLs or application logs.
- Plan for token expiration, key rotation, and revocation requirements.
A JWT is not automatically trustworthy because it is encoded as a token. Never use claims from an unvalidated token to make security decisions. Spring Security's OAuth 2.0 Resource Server support is generally preferable to writing custom token-validation logic.
Conceptual Stateless API Configuration
http
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(authorize -> authorize
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2
.jwt(Customizer.withDefaults())
);
This configuration outline requires the appropriate Spring Security OAuth 2.0 Resource Server dependencies and trusted JWT issuer or public-key configuration. Stateless session management alone does not implement authentication; the resource server must validate bearer tokens. Configure CSRF according to the actual client and credential model rather than disabling it indiscriminately.
17. Implementing Database-Backed Authentication
Production applications commonly store user records and role assignments in a database. A simple design may include a user table, a role table, and a join table associating users with roles.
Example User Table
| Column |
Purpose |
id |
Unique user identifier. |
username |
Unique login name. |
password_hash |
Encoded password value. |
enabled |
Indicates whether the account is enabled. |
Example Role Table
| Column |
Purpose |
id |
Unique role identifier. |
name |
Role name, such as ROLE_USER or ROLE_ADMIN. |
A user may have one or multiple roles depending on the application's requirements. A separate user-role join table is commonly used when users can hold multiple roles.
UserDetailsService Structure
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
public class CustomUserDetailsService
implements UserDetailsService {
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
// Find the user using a repository.
// Map the stored password hash and authorities
// to a Spring Security UserDetails object.
throw new UsernameNotFoundException(
"Implement database user lookup");
}
}
This is a structural example, not a complete implementation. A working service should query a user repository, handle missing or disabled accounts appropriately, and map stored roles to granted authorities. Passwords must be stored as secure hashes.
18. CSRF and CORS
Cross-Site Request Forgery (CSRF)
CSRF is an attack in which a browser is induced to send an unwanted authenticated request to an application. It is especially relevant when authentication relies on cookies that the browser sends automatically.
- Keep CSRF protection enabled for applications that need it.
- Include and validate CSRF tokens for relevant state-changing requests.
- Do not assume that CORS configuration replaces CSRF protection.
- Evaluate the risk of disabling CSRF based on the application's authentication design.
Cross-Origin Resource Sharing (CORS)
CORS determines which browser origins may access a resource through cross-origin requests. Configure allowed origins, methods, and headers as narrowly as practical.
For credentialed requests, specify trusted origins explicitly and configure credentials correctly. Do not combine unrestricted wildcard origins with credentialed access.
19. Testing Authentication and Authorization
Security testing should verify both successful access and denied access. Testing only valid logins can leave serious authorization problems undetected.
Testing Checklist
- Verify that public endpoints are accessible without authentication.
- Verify that protected endpoints reject unauthenticated requests.
- Verify that valid users can access permitted resources.
- Verify that USER accounts cannot access ADMIN-only endpoints.
- Verify that ADMIN accounts can access authorized administrative endpoints.
- Verify that invalid credentials do not establish authentication.
- Verify that disabled accounts are rejected.
- Verify session expiration and logout behavior where applicable.
- Verify CSRF handling for cookie-authenticated applications.
- Verify JWT signature, issuer, audience, and expiration checks where applicable.
Example Spring Security Test
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@SpringBootTest
@AutoConfigureMockMvc
class SecurityControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
void adminEndpointRejectsRegularUser() throws Exception {
mockMvc.perform(get("/api/admin")
.with(user("employee").roles("USER")))
.andExpect(status().isForbidden());
}
}
This test assumes that /api/admin is configured to require the ADMIN role and that the test security context is applied correctly. Add the Spring Security test dependency to use the testing helpers.
To test unauthenticated requests, assert the response configured by your authentication entry point. Depending on the application, a protected request may return 401 or redirect to a login page.
20. Common Problems and Troubleshooting
| Problem |
Possible Cause |
Solution |
| Requests redirect to login |
Form login is enabled or the request is not matched by the intended API configuration. |
Review security matchers and configure the appropriate authentication entry point. |
| Unexpected 401 response |
Missing or invalid credentials or bearer token. |
Check the authentication mechanism and request headers. |
| Unexpected 403 response |
Insufficient permissions or a failed CSRF check. |
Review authorization rules, authorities, and CSRF requirements. |
| Role checks fail |
Role prefix or authority mapping mismatch. |
Check the difference between hasRole and hasAuthority. |
| Password verification fails |
The stored password hash does not match the configured encoder or user lookup. |
Verify the stored hash and encoder configuration without logging passwords. |
| JWT is rejected |
Invalid signature, issuer, audience, expiration, or resource-server configuration. |
Inspect token claims and trusted issuer or key settings. |
| Cross-origin request fails |
The origin, method, or headers are not allowed. |
Configure the required trusted origins and request options. |
| CSRF errors occur |
A required CSRF token is missing or invalid. |
Ensure the client sends the correct token for the applicable request. |
21. Security Best Practices
- Use HTTPS for login pages, REST APIs, and sensitive traffic.
- Store passwords using a suitable adaptive password-hashing algorithm.
- Never hardcode production passwords, signing keys, or database credentials.
- Apply the principle of least privilege to roles and authorities.
- Protect both HTTP endpoints and sensitive service methods where appropriate.
- Use consistent error responses that do not expose internal implementation details.
- Keep Spring Boot and Spring Security dependencies updated.
- Configure session handling, secure cookies, and CSRF protection when applicable.
- Validate bearer tokens before trusting their claims.
- Rate-limit login attempts and monitor suspicious authentication activity.
- Never expose password hashes, session identifiers, access tokens, or secrets in logs.
- Test unauthorized and forbidden scenarios as part of the application's test suite.
- Use multi-factor authentication where required by the application's risk profile.
- Review access-control rules whenever a new endpoint or service method is introduced.
22. Practical Project: Secure Employee Management API
Project Objective: Develop a Spring Boot application that authenticates users and restricts employee-management operations according to their roles.
Functional Requirements
- Create a Spring Boot project with Spring Web and Spring Security.
- Define user and role models or start with an in-memory user store for a prototype.
- Configure secure password encoding.
- Create public endpoints for general information.
- Protect profile endpoints so only authenticated users can access them.
- Restrict employee creation, updating, and deletion to authorized roles.
- Return appropriate responses for unauthenticated and forbidden requests.
- Write tests for authentication and role-based access control.
- Document the security rules and authentication mechanism.
Example Endpoint Plan
| HTTP Method |
Endpoint |
Access Rule |
| GET |
/api/public/info |
Public |
| GET |
/api/profile |
Authenticated user |
| GET |
/api/employees |
Authenticated user with permitted access |
| POST |
/api/employees |
ADMIN role |
| PUT |
/api/employees/{id} |
ADMIN role or a specific authorized business rule |
| DELETE |
/api/employees/{id} |
ADMIN role |
For user-owned resources, a role check alone may not be sufficient. Verify that the authenticated user is permitted to access the specific record identified by the request.
23. Interview Questions and Answers
Q1. What is authentication?
Answer: Authentication verifies a user's identity by validating credentials or other identity evidence.
Q2. What is authorization?
Answer: Authorization determines whether an identity has permission to access a resource or perform an operation.
Q3. What is Spring Security?
Answer: Spring Security is a framework that provides authentication, authorization, password encoding, security filters, and protection against common web security threats.
Q4. What is SecurityFilterChain?
Answer: It defines the security filters and access rules applied to matching HTTP requests.
Q5. What is AuthenticationManager?
Answer: It coordinates authentication by delegating authentication requests to configured providers.
Q6. What is UserDetailsService?
Answer: It loads user-specific information, commonly by username, for username-and-password authentication.
Q7. Why is PasswordEncoder important?
Answer: It enables passwords to be stored as one-way hashes and verifies submitted passwords against the stored values without storing the original passwords.
Q8. What is the difference between hasRole and hasAuthority?
Answer: hasRole("ADMIN") conventionally checks for ROLE_ADMIN, while hasAuthority("REPORT_READ") checks for the exact authority supplied.
Q9. What is method-level security?
Answer: It applies access-control rules to service or other method invocations, often using annotations such as @PreAuthorize.
Q10. What is the difference between HTTP 401 and 403?
Answer: A 401 response generally indicates that acceptable authentication has not been established, while a 403 response generally indicates that the requested access is not permitted.
Q11. What is JWT?
Answer: JSON Web Token is a format for representing claims that can be cryptographically protected. A resource server must validate the token before trusting its claims.
Q12. What is CSRF?
Answer: Cross-site request forgery is an attack that attempts to cause a user's browser to submit an unwanted authenticated request. It is particularly relevant to cookie-based authentication.
Q13. What is the principle of least privilege?
Answer: It means granting each user or system only the permissions needed to perform its intended tasks.
Q14. Why is HTTPS important?
Answer: HTTPS protects credentials, tokens, cookies, and application data in transit from eavesdropping and tampering.
24. Quick Revision Checklist
- Authentication verifies identity; authorization evaluates permissions.
- Spring Security uses a filter chain to process and secure HTTP requests.
SecurityFilterChain defines request-matching and access-control rules.
UserDetailsService loads user information for username-based authentication.
PasswordEncoder supports secure password storage and verification.
hasRole and hasAuthority perform different authorization checks.
@EnableMethodSecurity enables method-level security.
- Use appropriate 401 and 403 responses for authentication and authorization failures.
- Validate bearer tokens before trusting their claims.
- Protect cookie-based applications against CSRF where applicable.
- Apply least privilege, use HTTPS, and test denied-access scenarios.
25. Conclusion
Authentication and authorization are essential for building secure Java web applications. Spring Security provides reusable components for verifying identities, loading user information, encoding passwords, and enforcing role-based or authority-based access rules.
By configuring SecurityFilterChain, protecting stored passwords, applying method-level security where needed, and testing both successful and rejected requests, developers can create applications with reliable security boundaries.
To continue learning, explore the Advanced Java Training course, visit the JustAcademy website, or register for a course demo.
26. Further Reading